package ar.org.cfired.creditos.webservices;

import java.util.List;
import java.util.ArrayList;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.HibernateException;
import org.hibernate.Query;

/**
 * Administra logins para los web services
 * @author Rogelio Di Pasquale - Revolution BPM
 *
 */
public class WebServiceLogin {
	private Integer id;
	private String nombre;
	private String descripcion;
	private List<String> provincias;

	public WebServiceLogin () {
		provincias = new ArrayList<String>();
	}
	
	
	public void setId(Integer i) {
		id = i;
	}
	public Integer getId() {
		return(id);
	}
	
	public void setNombre(String n) {
		nombre = n;
	} 
	public String getNombre() {
		return(nombre);
	}

	public void setDescripcion(String n) {
		descripcion = n;
	} 
	public String getDescripcion() {
		return(descripcion);
	}
	
	public void addProvincia(String n) {
		provincias.add(n);
	} 
	public List<String> getProvincias() {
		return(provincias);
	}

	 public static byte[] computeHash(String x)   
	  throws Exception  
	  {
	     java.security.MessageDigest d =null;
	     d = java.security.MessageDigest.getInstance("SHA-1");
	     d.reset();
	     d.update(x.getBytes());
	     return  d.digest();
	  }

	 public static String byteArrayToHexString(byte[] b){
		     StringBuffer sb = new StringBuffer(b.length * 2);
		     for (int i = 0; i < b.length; i++){
		       int v = b[i] & 0xff;
		       if (v < 16) {
		         sb.append('0');
		       }
		       sb.append(Integer.toHexString(v));
		     }
		     return sb.toString().toUpperCase();
		  }

	public static WebServiceLogin login (String usuario, String password, Session session) throws WebServiceLoginFailedException{
		WebServiceLogin rta = null;
		Transaction t = null;
		boolean sinSesion = (!session.getTransaction().isActive()); 
		if (sinSesion) {
			 t = session.beginTransaction();
		}
		try {
			Query q = session.getNamedQuery("ws_user_login");
			q.setString("usuario", usuario);
			q.setBinary("password", computeHash(password));
			List<String> l = (List<String>)q.list();
			if (l.size() > 0) {
				rta = new WebServiceLogin();
				rta.setNombre(usuario);				
				for (int i = 0; i<l.size(); i++)
					rta.addProvincia(l.get(i));
			}
			else {
				throw new WebServiceLoginFailedException();
			}
		}
		catch (HibernateException e){
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			if (sinSesion)
				if (t!=null)
					if (t.isActive())
						t.rollback();
		}
		
		
		return (rta);
	}
}

